import { Strategy, ExtractJwt, StrategyOptions } from 'passport-jwt';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { jwtConstants } from './constants';
import { RedisCacheService } from 'src/component/redis/redis-cache.service';
import { Request } from 'express';
import { ToolsService } from 'src/utils/tools.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private redisService: RedisCacheService) {
    super({
      jwtFromRequest: ExtractJwt.fromHeader('token'), //使用ExtractJwt.fromHeader从header获取token
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret, //使用密钥解析，可以使用process.env.xxx
      passReqToCallback: true,
    } as StrategyOptions);
  }

  //token验证, payload是super中已经解析好的token信息
  async validate(req: Request, payload: any) {
    console.log(payload);
    const { id } = payload;
    try {
      const token = ExtractJwt.fromHeader('token')(req);
      const cacheToken = await this.redisService.get(`user-token-${id}`);
      //获取redis的key;
      //单点登陆验证
      if (token !== JSON.parse(cacheToken)) {
        ToolsService.fail('Token已过期登陆，请重新登陆', 401);
      }
      return { username: payload.username, userid: payload.id };
    } catch (error) {
      ToolsService.fail('登录异常？请重新登录', 401);
    }
  }
}
